package service

import (
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	constant "rongyy/src/constants"
	"rongyy/src/helper"
	"rongyy/src/middlewares"
	"rongyy/src/models"
	"time"
)

type MerchantService struct {
}

func (us *MerchantService) UserWxInfo(req *models.UserModel) (*models.UserModel, bool, error) {
	data, has, err := (&models.UserModel{}).FindByUnionid(req.Unionid)
	if err != nil {
		middlewares.Logger.Println("UserWxInfo ", err)
		return nil, false, err
	}
	return data, has, nil
}

func (us *MerchantService) Profile(req *models.UserModel) ([]models.CardModel, int64, error) {
	data, total, err := (&models.UserModel{}).FindCardsByUnionid(req.Unionid)
	//for _,item := range data {

	var i int
	for i = 0; i < len(data); i++ {
		if len(data[i].IdNo) > 15 {
			data[i].Age = helper.GetAgeByBirthday(data[i].IdNo)
			data[i].IdNo = data[i].IdNo[0:3] + "***********" + data[i].IdNo[14:]
		}
	}
	if err != nil {
		middlewares.Logger.Println("Unmarshal GetHisBills failed ", err)
		return nil, 0, err
	}
	middlewares.Logger.Println("Profile====", data)
	return data, total, nil
}

func (u *MerchantService) Create(merchant *models.MerchantModel) (string, error) {
	data, err := merchant.Create()
	if err != nil {
		middlewares.Logger.Println("Unmarshal GetHisBills failed ", err)
		return "", err
	}
	fmt.Println(data)
	token, err := GenerateToken(data.Id)
	if err != nil {
		middlewares.Logger.Println("merchant GenerateToken failed ", err)
		return "", err
	}
	return token, nil
}

func GenerateToken(merchantId int64) (string, error) {
	claims := jwt.MapClaims{}
	claims["authorized"] = true
	claims["merchant_id"] = merchantId
	claims["exp"] = time.Now().Add(time.Hour * 24 * 10).Unix()
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	tokenString, err := token.SignedString(constant.JwtSecret)
	if err != nil {
		return "", err
	}

	return tokenString, nil
}

func (u *MerchantService) FindByUnionid(unionid string) (*models.UserModel, bool, error) {
	data, has, err := (&models.UserModel{}).FindByUnionid(unionid)
	if err != nil {
		middlewares.Logger.Println("Unmarshal GetHisBills failed ", err)
		return nil, false, err
	}
	return data, has, err
}

func (ps *MerchantService) WxLogin(req *models.ReqWxLogin) (interface{}, error) {
	// var userData = map[string]interface{}{}
	// sessionKey, _ := base64.StdEncoding.DecodeString(req.Code)
	// iv, _ := base64.StdEncoding.DecodeString(req.Iv)
	// encryptData, _ := base64.StdEncoding.DecodeString(req.EncryptedData)
	// cipherBlock, _ := aes.NewCipher(sessionKey)
	// mode := cipher.NewCBCDecrypter(cipherBlock, iv)
	// mode.CryptBlocks(encryptData, encryptData)
	// decrypted := unPad(encryptData)
	// _ = json.Unmarshal(decrypted, &userData)
	// middlewares.Logger.Printf("userData %#v", userData)

	respWxSession, err := helper.Code2Session(req.Code)
	if err != nil {
		return nil, errors.New("登录失败，微信Code2Session时出错。")
	}
	wxUser := &models.UserModel{}
	middlewares.Logger.Printf("WxLogin Unionid %#v", respWxSession.Unionid)
	wxUser.Unionid = respWxSession.Unionid
	exist, err := wxUser.Get()
	if err != nil {
		return nil, errors.New("登录失败，查询微信用户数据时出错。")
	}
	if !exist {
		wxUser.Unionid = respWxSession.Unionid
		wxUser.MpOpenid = respWxSession.Openid
		wxUser.Nickname = req.UserInfo.Nickname
		//wxUser.Gender = req.UserInfo.Gender
		wxUser.Language = req.UserInfo.Language
		wxUser.City = req.UserInfo.City
		wxUser.Province = req.UserInfo.Province
		wxUser.Country = req.UserInfo.Country
		//wxUser.AvatarUrl = req.UserInfo.AvatarUrl
		err = wxUser.Insert()
		if err != nil {
			return nil, errors.New("登录失败，缓存微信用户数据时出错。")
		}
	}

	wxUser.MpOpenid = respWxSession.Openid
	err = wxUser.UpdateMpOpenid(respWxSession.Unionid)
	if err != nil {
		return nil, errors.New("登录失败，查询微信用户数据时出错。")
	}
	wxUser.Unionid = respWxSession.Unionid
	pcs, _, err := ps.Profile(wxUser)
	if err != nil {
		return nil, err
	}

	return map[string]interface{}{"wx": wxUser, "list": pcs, "union_id": wxUser.Unionid}, nil
}
